package xiaomo.example.ordercore.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xiaomo.example.accountapi.AmountFeignClient;
import xiaomo.example.accountapi.amount.bo.AmountDecreaseBo;
import xiaomo.example.ordercore.bo.OrderBO;
import xiaomo.example.storageapi.ProductFeignClient;
import xiaomo.example.storageapi.product.bo.ProductDecreaseBO;

@Api(tags = "订单管理")
@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private AmountFeignClient amountFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 订单的创建
     * @param bo 订单详细信息
     * @return   订单创建情况
     */
    @ApiOperation("创建订单")
    @PostMapping("create")
    public String create(@RequestBody OrderBO bo){
    log.info("订单服务：创建订单：{}",bo);
    /**
     * 调用账户服务扣减余额
     */
    AmountDecreaseBo amountDecreaseBo=new AmountDecreaseBo();
    amountDecreaseBo.setAmount(bo.getAmount());
    amountDecreaseBo.setUserId(bo.getUserId());
    amountFeignClient.decreaseMoney(amountDecreaseBo);
    /**
     * 调用库存服务扣减库存
     */
    ProductDecreaseBO productDecreaseBO=new ProductDecreaseBO();
    productDecreaseBO.setCount(bo.getCount());
    productDecreaseBO.setProductId(bo.getProductId());
    productFeignClient.decreaseStorage(productDecreaseBO);
        return "订单创建成功";
    }


    /**
     * 在减库存时刻意抛出异常
     * @param orderBO 订单详细信息
     * @return 订单创建情况
     */
    @ApiOperation("创建订单（抛异常）")
    @PostMapping("createFault")
    public String createFault(@RequestBody OrderBO orderBO) {
        log.error("订单服务：创建订单刻意抛出异常：{}", orderBO);

        /**
         * 调用库存服务扣减库存
         */
        ProductDecreaseBO productDecreaseBO = new ProductDecreaseBO();
        productDecreaseBO.setProductId(orderBO.getProductId());
        productDecreaseBO.setCount(orderBO.getCount());
        productFeignClient.decreaseStorageFault(productDecreaseBO);

        /**
         * 调用账户服务扣减余额
         */
        AmountDecreaseBo amountDecreaseBO = new AmountDecreaseBo();
        amountDecreaseBO.setUserId(orderBO.getUserId());
        amountDecreaseBO.setAmount(orderBO.getAmount());
        amountFeignClient.decreaseMoney(amountDecreaseBO);

        return "创建订单成功";
    }

}
